package com.huluobo.a2203kotlindouyindemo.login

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.huluobo.a2203kotlindouyindemo.MainActivity
import com.huluobo.a2203kotlindouyindemo.R
import com.huluobo.a2203kotlindouyindemo.databinding.ActivityLoginBinding
import com.huluobo.base.bean.Money
import com.huluobo.base.db.AppDBUtils
import com.huluobo.base.net.Const
import com.huluobo.base.view.BaseMVVMActivity
import com.hyphenate.EMCallBack
import com.hyphenate.chat.EMClient

class LoginActivity : BaseMVVMActivity<ActivityLoginBinding, LoginViewModel>() {
    override fun initData() {
        viewModel.loginSuccess.observe(this) {
            if (it.code == 200) {
                EMClient.getInstance().login(it.data.username, it.data.password, object : EMCallBack {
                    override fun onSuccess() {
                        ToastUtils.showLong("欢迎回来:${it.data.username}")
                        SPUtils.getInstance().put(Const.PARAM_TOKEN, it.data.token)
                        SPUtils.getInstance().put(Const.PARAM_USERNAME, it.data.username)
                        SPUtils.getInstance().put(Const.PARAM_ADDRESS, it.data.address)
                        AppDBUtils.getDb().getUserDao().insertUserInfo(it.data)
                        val money = Money(0L, it.data.username, 10000F)
                        AppDBUtils.getDb().getMoneyDao().insertUserMoney(money)
                        val intent = Intent(this@LoginActivity, MainActivity::class.java)
                        startActivity(intent)
                        finish()
                    }

                    override fun onError(code: Int, error: String?) {
                        Log.i("TagA", "登录环信失败:$code,error:$error")
                    }
                })
            }
        }
    }

    override fun initView() {
        dataBinding.loginToLoginBtn.setOnClickListener {
            viewModel.login(
                dataBinding.loginUsernameEt.text.toString(),
                dataBinding.loginPasswordEt.text.toString()
            )
        }
    }

    override fun getViewModel(): Class<LoginViewModel> {
        return LoginViewModel::class.java
    }

    override fun getLayoutId(): Int = R.layout.activity_login
}